package com.dld.android.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Process;
import android.util.Log;

import com.dld.android.util.LogUtils;

/**
 * 网络协议
 * 
 * @author
 * 
 */
public class Http extends Connector {
	private Callback callback;
	private boolean cancel;
	private HttpConfig config;
	private HttpURLConnection conn;
	private InputStream in;
	private OutputStream outputstream;

	static {
		HttpURLConnection.setDefaultAllowUserInteraction(true);
		HttpURLConnection.setFollowRedirects(true);
	}

	public Http(Callback paramCallback, HttpConfig paramHttpConfig) {
		this.callback = paramCallback;
		this.config = paramHttpConfig;
	}

	private byte[] readToByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
		int len = 0;
		byte[] buffer = new byte[1024];
		while ((len = input.read(buffer)) > 0) {
			bout.write(buffer, 0, len);
		}
		return bout.toByteArray();
	}

	private void doRun() {

		try {
			Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
			URL url = new URL(this.callback.getUrl());
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(20 * 1000);
			conn.connect();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				HttpURLConnection.setFollowRedirects(true);
				InputStream input = conn.getInputStream();
				this.callback.onRecieve(readToByteArray(input));
			} else {
				this.callback.onException(new Exception());
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.callback.onException(e);
		} finally {
			Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
		}

	}

	public void close() {
		try {
			if (this.outputstream != null) {
				this.outputstream.close();
				this.outputstream = null;
			}
			if (this.in != null) {
				this.in.close();
				this.in = null;
			}
			if (this.conn != null) {
				this.conn.disconnect();
				this.conn = null;
			}
		} catch (Exception localException) {
			LogUtils.e("test", localException);
		}
	}

	public void run() {
		doRun();

	}
}
